import React from "react";
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'
import { Button, message } from 'antd'
import { EditableTitle } from "../common";
import { SaveOutlined, EditOutlined } from '@ant-design/icons';
import axios from "axios";
import { Url } from "../url";
import 'braft-editor/dist/output.css'

import { Typography, Space } from 'antd';


const { Text, Link, Title } = Typography;

export class NewsDetail extends React.Component {

    editTitle = "";
    state = {
        detailHtml: "<div>No new found</div>",
        editorState: null,
        title: "Input Your Title Here",
        editMode: true,
        editTime: (new Date()).getTime(),
        author: "unknown"
    }

    handleEditorChange = (editorState) => {
        this.setState({ editorState })

    }

    publishNews = () => {

        if (this.editTitle == undefined || this.editTitle === "") {
            message.error("You have to input a title");
        } else if (this.state.editorState == undefined) {
            message.error("You have to input documents.");
        }

        else {
            const htmlContent = this.state.editorState.toHTML()
            const payload = {
                id: this.props.match.params.id === "publish" ? undefined : this.props.match.params.id,
                title: this.editTitle,
                author: this.user.userId,
                detail: htmlContent,
                mongodbId: undefined
            };

            axios.post(Url.publishNews, payload).then((response => {
                message.success("Save news success.");
                setTimeout(() => {
                    window.location.href = "/#/admin/news/" + response.data.id + "?_time=" + (new Date()).getTime();
                }, 50);
            })).catch((error) => {
                message.error("Save news error.")
            });
        }
    }

    user={};
    componentDidMount = () => {
        let userString = localStorage.getItem("user")
        if (userString == null) {
            setTimeout(() => {
                window.location.href = "/#/login";
            }, 500);
        } else {
            this.user=JSON.parse(userString)
            this.props.history.listen(() => {
                this.init();
            });

            this.init();
        }

    }

    init = () => {
        if (this.props.match.params.id === "publish") {
            this.setState({
                editMode: true
            });
        } else {
            this.getNews();
        }
    }

    getNews = () => {
        this.setState({
            editMode: false
        });
        axios.get(Url.viewNews + this.props.match.params.id).then((response) => {

            this.editTitle = response.data.title;
            this.setState({
                detailHtml: response.data.detail,
                author: response.data.author,
                editTime: response.data.editTime,
                title: response.data.title,
                mongodbId: response.data.id
            });

        }).catch(() => {
            message.error("View news error.")
        });
    }


    editMode = () => {

        const editorState = BraftEditor.createEditorState(this.state.detailHtml);
        this.setState({
            editMode: true,
            editorState: editorState
        });
    }


    render = () => {


        let body = <></>

        if (this.state.editMode) {
            const { editorState } = this.state
            body = <div>
                <div style={{ marginBottom: "16px", marginTop: "32px" }}>
                    <Title level={2} editable={{
                        onChange: (title) => {
                            this.editTitle = title;
                            this.setState({
                                title: title
                            })
                        }
                    }}>{this.state.title}</Title>
                </div>

                <BraftEditor
                    value={editorState}
                    onChange={this.handleEditorChange}
                    language="en"
                    style={{ border: "2px solid #ddd", borderRadius: 10 }}
                />
                <Button type="primary" icon={<SaveOutlined />} shape="round" style={{ marginTop: "16px", marginBottom: "16px" }} onClick={this.publishNews}>
                    Save
                </Button>

            </div>
        } else {
            body =
                <div>
                    <div style={{ marginBottom: "16px", marginTop: "32px" }}>
                        <Title level={2}>{this.state.title}</Title>
                    </div>
                    <div style={{ marginBottom: "32px" }}>
                        <Text italic>
                            {(new Date(this.state.editTime)).toLocaleDateString() + " " + (new Date(this.state.editTime)).toLocaleTimeString()}, edited by {this.state.author}

                            {this.user.admin?<Button type="text" onClick={this.editMode}><EditOutlined /></Button>:<span></span>}
                        </Text>
                    </div>
                    <div dangerouslySetInnerHTML={{ __html: this.state.detailHtml }}>
                    </div>
                </div>
        }

        return (

            <div style={{ width: "100%", display: "flex", justifyContent: "center" }}>
                <div style={{ width: "80%" }}>
                    {body}
                    <div style={{ marginTop: "32px" }}></div>
                </div>
            </div>
        )
    }
}